//
//  ScriptMessageHandler.swift
//  ADKit
//
//  Created by Adoma on 2020/10/29.
//

import Foundation
import WebKit
import SwiftyJSON

public struct MessageHandler {
    var name: String
    var handler: (JSON)->Void
    
    public init(name: String, handler: @escaping (JSON)->Void) {
        self.name = name
        self.handler = handler
    }
}

public final class ScriptMessageHandler: NSObject, WKScriptMessageHandler {
    
    var handlers: [MessageHandler]
    fileprivate weak var controller: WKUserContentController?
    
    public init(handlers: [MessageHandler]) {
        self.handlers = handlers
        super.init()
    }
    
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        for handler in handlers {
            guard handler.name == message.name else {
                continue
            }
            handler.handler(JSON.init(message.body))
            break
        }
    }
    
    public func removeFromController() {
        handlers.forEach {
            self.controller?.removeScriptMessageHandler(forName: $0.name)
        }
    }
    
    deinit {
        ADLogger(adkit: Self.self)
            .debug(#function)
    }

}

public extension WKUserContentController {
    
    func add(handler: ScriptMessageHandler) {
        handler.controller = self
        handler.handlers.forEach {
            self.add(handler, name: $0.name)
        }
    }
    
}


